package com.moyun.zbmy.zizhou.ui.dialog;

import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.text.TextUtils;
import android.util.Pair;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.GridView;
import android.widget.LinearLayout;
import android.widget.Toast;

import com.jiongbull.jlog.JLog;
import com.ruihang.generalibrary.beans.ShareItem;
import com.ruihang.generalibrary.ui.adapter.ShareGrideAdapter;
import com.ruihang.generalibrary.ui.dialog.BaseBottomSheetFrag;
import com.ruihang.generalibrary.ui.dialog.ShareFragment;
import com.ruihang.generalibrary.ui.widget.CustomFontTextView;
import com.ruihang.generalibrary.utils.IShares;
import com.moyun.zbmy.zizhou.R;
import com.moyun.zbmy.zizhou.ui.utils.UIUtils;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import cn.sharesdk.framework.Platform;
import cn.sharesdk.framework.PlatformActionListener;
import cn.sharesdk.onekeyshare.OnekeyShare;
import cn.sharesdk.sina.weibo.SinaWeibo;
import cn.sharesdk.system.email.Email;
import cn.sharesdk.tencent.qq.QQ;
import cn.sharesdk.tencent.qzone.QZone;
import cn.sharesdk.wechat.friends.Wechat;
import cn.sharesdk.wechat.moments.WechatMoments;

public class ShareAdvertImageFragment extends BaseBottomSheetFrag implements AdapterView.OnItemClickListener
        , PlatformActionListener {

    private IShares shares;
    private String shareType;

    private GridView shareList;
    private CustomFontTextView cancel;
    private ShareGrideAdapter shareAdapter;

    private ShareSuccess listener;
    private static final int WHAT_ERROR = 1;
    private static final int WHAT_CANCLE = 2;
    private static final int WHAT_SUC = 3;
    private Pair<String, String> pairs;
    private ShareFragment.OnShareFragmentClickListener onShareFragmentClickListener;
    private static final String HAIBAO = "haibao";
    private boolean isLoad = false;
    private boolean isHideHaiBao = false;
    private boolean isImageInitFinish = false;
    private boolean isViewInitFinish = false;
    private boolean isGlideInitFinish = false;
//    private Handler handler;

    Bitmap shareBit;

    public void setHideHaiBao(boolean hideHaiBao) {
        isHideHaiBao = hideHaiBao;
    }

    public void setShareSuccessListener( ShareSuccess listener) {
        this.listener = listener;
    }

    public void setOnShareFragmentClickListener(ShareFragment.OnShareFragmentClickListener onShareFragmentClickListener) {
        this.onShareFragmentClickListener = onShareFragmentClickListener;
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        return super.onCreateView(inflater, container, savedInstanceState);

    }

    @Override
    public int getLayoutResId() {
        return R.layout.dia_share_advert_img;
    }

    public void initView() {

        shareList = (GridView) rootView.findViewById(R.id.share_list);
        WindowManager wm = (WindowManager) getActivity().getSystemService(Context.WINDOW_SERVICE);
        int width = wm.getDefaultDisplay().getWidth();
        ViewGroup.LayoutParams lp = shareList.getLayoutParams();
        lp.width = width;
        List<ShareItem> list = new ArrayList<>();
        list.add(new ShareItem(com.ruihang.generalibrary.R.drawable.icon_share_wx, com.ruihang.generalibrary.R.string.share_weixin).setTag(Wechat.NAME));
        list.add(new ShareItem(com.ruihang.generalibrary.R.drawable.icon_share_wfcircle, com.ruihang.generalibrary.R.string.share_pyq).setTag(WechatMoments.NAME));
        list.add(new ShareItem(com.ruihang.generalibrary.R.drawable.icon_share_qq, com.ruihang.generalibrary.R.string.share_qq).setTag(QQ.NAME));
        list.add(new ShareItem(com.ruihang.generalibrary.R.drawable.icon_share_qspace, com.ruihang.generalibrary.R.string.share_qq_space).setTag(QZone.NAME));
//        list.add(new ShareItem(com.ruihang.generalibrary.R.drawable.icon_share_wb, com.ruihang.generalibrary.R.string.share_sina).setTag(SinaWeibo.NAME));
//        list.add(new ShareItem(com.ruihang.generalibrary.R.drawable.icon_share_email, com.ruihang.generalibrary.R.string.share_eamil).setTag(Email.NAME));
        //     list.add(new ShareItem(com.ruihang.generalibrary.R.drawable.mine_icon_mail, com.ruihang.generalibrary.R.string.share_eamil).setTag(Email.NAME));
//        list.add(new ShareItem(R.drawable.icon_share_system, R.string.share_system).setTag("System"));
//        list.add(new ShareItem(R.drawable.share_tencent,R.string.share_tencent).setTag(TencentWeibo.NAME));

//        changeGridView(shareList, list);
        shareAdapter = new ShareGrideAdapter(getContext(), list);
        shareList.setAdapter(shareAdapter);
        shareList.setOnItemClickListener(this);
        cancel = (CustomFontTextView) rootView.findViewById(R.id.share_cancel);
        cancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                ShareAdvertImageFragment.this.dismissAllowingStateLoss();
            }
        });
    }


    /**
     * 加载本地图片
     *
     * @param url
     * @return
     */
    public static Bitmap getLoacalBitmap(String url) {
        try {
            FileInputStream fis = new FileInputStream(url);
            return BitmapFactory.decodeStream(fis);  ///把流转化为Bitmap图片

        } catch (FileNotFoundException e) {
            e.printStackTrace();
            return null;
        }
    }

    public IShares getShares() {
        return shares;
    }

    public void setShares(IShares shares) {
        this.shares = shares;
    }


    private void setSharePlatform(Platform form, IShares shares) {
        form.setPlatformActionListener(this);

    }

    private Platform.ShareParams getShareParams(String name, IShares ishares) {
        JLog.e("ishare=" + ishares);
        Platform.ShareParams sp = null;
        boolean setUrl = true;
        boolean isWebPage = true;
        boolean isQQ = false;
        if (QQ.NAME.equals(name)) {
            shareType = "分享到QQ好友";
            sp = new QQ.ShareParams();
            isQQ = true;
            pairs = new Pair<>("行为类型", "分享到QQ好友");
        } else if (QZone.NAME.equals(name)) {
            shareType = "分享到QQ空间";
            sp = new QZone.ShareParams();
            pairs = new Pair<>("行为类型", "分享到QQ空间");
        } else if (Wechat.NAME.equals(name)) {
            shareType = "分享到微信好友";
            sp = new Wechat.ShareParams();
            pairs = new Pair<>("行为类型", "分享到微信好友");
        } else if (WechatMoments.NAME.equals(name)) {
            shareType = "分享到朋友圈";
            sp = new WechatMoments.ShareParams();
            pairs = new Pair<>("行为类型", "分享到朋友圈");
        } else if (SinaWeibo.NAME.equals(name)) {
            shareType = "分享到微博";
            sp = new SinaWeibo.ShareParams();
            setUrl = false;
            isWebPage = false;
            pairs = new Pair<>("行为类型", "分享到微博");
        } else if (Email.NAME.equals(name)) {
            shareType = "分享到电子邮箱";
            sp = new Email.ShareParams();
            pairs = new Pair<>("行为类型", "分享到电子邮箱");
        }

        if (sp != null) {
//            sp.setTitle(ishares.getShareTitle());
//            sp.setTitleUrl(ishares.getShareURL());
//            if (setUrl) {
//                sp.setUrl(ishares.getShareURL());
//            }
            sp.setTitle(null);
            sp.setText(null);
//            shareBit = UIUtils.createViewBitmap(shareView);
//            if (null != shareBit) {
//                String path = UIUtils.initImagePath(shareBit, "shareImage.jpg ");
            if (TextUtils.isEmpty(ishares.getShareImage())) {
                Toast.makeText(getContext(), "请先设置APP存储权限！", Toast.LENGTH_LONG).show();
                return null;
            } else {
                sp.setImagePath(ishares.getShareImage());
            }
//            } else {
//                return null;
//            }
            sp.setShareType(Platform.SHARE_IMAGE);
//            sp.setImageUrl("http://file.qcrmt.com/sctv/logo/logo.png");
//            sp.setTitleUrl(ishares.getShareURL());
//            sp.setSiteUrl("http://www.sctv.cn");
//            sp.setSite(this.getString(com.ruihang.generalibrary.R.string.app_name));
//            sp.setText("熊猫家园·大美青川，欢迎您");
//            if (SinaWeibo.NAME.equals(name)) {
//                sp.setText(ishares.getShareTitle() + " " + ishares.getShareURL());
//                if (!isValidClientSina("com.sina.weibo")) {
//                    sp.setUrl(ishares.getShareURL());
//                }
//            }
        } else {
            JLog.e("have none match :" + name);
        }
        return sp;
    }

    @Override
    public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
        JLog.e("in item click pos:" + i);
        if (shares == null) {
            toast("数据错误");
            return;
        }
        ShareItem si = shareAdapter.getItem(i);
        JLog.e("pos:" + i + " shares:" + shares + " item:" + si);
        if (si == null || TextUtils.isEmpty(si.getTag())) {
            toast("组件数据错误");
            return;
        }
        String tag = si.getTag();
        showShare(shares,true,tag);
        if (onShareFragmentClickListener != null && pairs != null) {
            onShareFragmentClickListener.onClick(pairs);
        }
//        dismiss();
    }

    private void showShare(IShares ishares, boolean silent, String platform) {
        OnekeyShare oks = new OnekeyShare();
        //关闭sso授权
        oks.disableSSOWhenAuthorize();
        oks.setSilent(silent);
        if (platform != null) {
            oks.setPlatform(platform);
        }
        if(QQ.NAME.equalsIgnoreCase(platform)){
            oks.setImageUrl(ishares.getShareImage());//分享网络图片
        }else {
            // 分享时Notification的图标和文字  2.5.9以后的版本不     调用此方法
            //oks.setNotification(R.drawable.ic_launcher, getString(R.string.app_name));
            // title标题，印象笔记、邮箱、信息、微信、人人网和QQ空间使用
            oks.setTitle(ishares.getShareTitle());
            // titleUrl是标题的网络链接，仅在人人网和QQ空间使用
            oks.setTitleUrl(ishares.getShareURL());
            // text是分享文本，所有平台都需要这个字段
            oks.setText("熊猫家园·大美青川，欢迎您");
            // imagePath是图片的本地路径，Linked-In以外的平台都支持此参数
            oks.setImageUrl(ishares.getShareImage());//分享网络图片
            // url仅在微信（包括好友和朋友圈）中使用
            oks.setSiteUrl("http://www.sctv.cn");

            // site是分享此内容的网站名称，仅在QQ空间使用
            oks.setSite(getString(R.string.app_name));
        }
        // 启动分享GUI
        oks.show(getContext());
    }


    @Override
    public void onDestroy() {
        super.onDestroy();
        if (null != shareBit && !shareBit.isRecycled()) {
            shareBit.recycle();
            shareBit = null;
        }
    }

    @Override
    public void onComplete(Platform platform, int i, HashMap<String, Object> hashMap) {
        handler.sendEmptyMessage(WHAT_SUC);
    }

    @Override
    public void onError(Platform platform, int i, Throwable throwable) {
        Message msg = Message.obtain();
        msg.what = WHAT_ERROR;
        msg.obj = "分享失败";
        if (throwable != null) {
            throwable.printStackTrace();
            JLog.e("msg:" + throwable.getMessage() + "\ncause:" + throwable.getCause()
                    + "\n" + throwable.getLocalizedMessage());
            String expName = throwable.getClass().getSimpleName();
            String strName = null;
            if ("WechatClientNotExistException".equals(expName)
                    || "WechatTimelineNotSupportedException".equals(expName)
                    || "WechatFavoriteNotSupportedException".equals(expName)) {
                strName = "ssdk_wechat_client_inavailable";
            } else if ("GooglePlusClientNotExistException".equals(expName)) {
                strName = "ssdk_google_plus_client_inavailable";
            } else if ("QQClientNotExistException".equals(expName)) {
                strName = "ssdk_qq_client_inavailable";
            } else if ("YixinClientNotExistException".equals(expName)
                    || "YixinTimelineNotSupportedException".equals(expName)) {
                strName = "ssdk_yixin_client_inavailable";
            } else if ("KakaoTalkClientNotExistException".equals(expName)) {
                strName = "ssdk_kakaotalk_client_inavailable";
            } else if ("KakaoStoryClientNotExistException".equals(expName)) {
                strName = "ssdk_kakaostory_client_inavailable";
            } else if ("WhatsAppClientNotExistException".equals(expName)) {
                strName = "ssdk_whatsapp_client_inavailable";
            } else if ("FacebookMessengerClientNotExistException".equals(expName)) {
                strName = "ssdk_facebookmessenger_client_inavailable";
            } else if (throwable.getMessage() != null && throwable.getMessage().contains("invalid_access_token")) {
                strName = "权限错误:" + throwable.getMessage();
            } else {
                strName = "ssdk_oks_share_failed";
            }

            if (strName != null) {
//                int resId = com.mob.tools.utils.R.getStringRes(getContext(), strName);
                int resId = com.mob.tools.utils.ResHelper.getStringRes(getContext(), strName);
                if (resId > 0) {
                    msg.obj = getContext().getString(resId);
                }
            }
//            toast(throwable.getMessage());
        }
        handler.sendMessage(msg);
    }

    @Override
    public void onCancel(Platform platform, int i) {
        JLog.e("ShareFragment ", "------onCancel--------");
        handler.sendEmptyMessage(WHAT_CANCLE);
    }

    public void shareBySystem(IShares shares) {
        Intent shareIntent = new Intent(Intent.ACTION_SEND);
        shareIntent.setType("image/*");
        shareIntent.putExtra(Intent.EXTRA_TEXT, shares.getShareTitle());
//        shareIntent.putExtra(Intent.)
        startActivity(Intent.createChooser(shareIntent, getString(com.ruihang.generalibrary.R.string.share_system_title)));
    }

    /**
     * 将GridView改成单行横向布局
     */
    private void changeGridView(GridView view, List<ShareItem> list) {
        // item宽度
        int itemWidth = UIUtils.dip2px(getContext(), 80);
        // item之间的间隔
        int itemPaddingH = UIUtils.dip2px(getContext(), 1);
        int size = list.size();
        // 计算GridView宽度
        int gridviewWidth = size * (itemWidth + itemPaddingH);

        LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(
                gridviewWidth, LinearLayout.LayoutParams.MATCH_PARENT);
        view.setLayoutParams(params);
        view.setColumnWidth(itemWidth);
        view.setHorizontalSpacing(itemPaddingH);
        view.setStretchMode(GridView.NO_STRETCH);
        view.setNumColumns(size);
    }


    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            if (msg == null) {
                return;
            }
            JLog.e("msg:" + msg);
            switch (msg.what) {
                case WHAT_ERROR:
                    toast((String) msg.obj);
                    break;
                case WHAT_CANCLE:
                    toast("分享取消");
                    break;
                case WHAT_SUC:
                    toast("分享成功");
                    if (null != listener) {
                        listener.OnShareSuccess(shareType);
                    }
                    dismissAllowingStateLoss();
                    break;
            }
        }
    };



    public interface ShareSuccess {
        void OnShareSuccess(String shareTpye);
    }
}
